package com.yjy.controller;

import com.yjy.common.Result;
import com.yjy.entity.Account;
import com.yjy.entity.Admin;
import com.yjy.entity.User;
import com.yjy.exception.CustomerException;
import com.yjy.service.AdminService;
import com.yjy.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
public class WebController {

    @Resource
    private AdminService adminService;

    @Resource
    private UserService userService;

    //测试用的
    @GetMapping("/hello")
    public Result hello(){
//        int a = 1/0;//RuntimeException 500 错误:常见的系统错误 抛出这些错误非常不友好 我们应该
        HashMap<Object,Object> map = new HashMap<>();
        map.put("name","yjy");
        return Result.success(map);
    }

    @GetMapping("/admin")
    public Result admin(String name) {
        String admin = adminService.admin(name);
        return Result.success(admin);
    }

    @PostMapping("/login")
    public Result login(@RequestBody Account account){
        Account dbAccount = null;
        if("ADMIN".equals(account.getRole())) {
            dbAccount = adminService.login(account);
        }else if("USER".equals(account.getRole())){
            dbAccount = userService.login(account);
        }else{
            throw new CustomerException("非法请求");
        }
        return Result.success(dbAccount);
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user){
       userService.register(user);
        return Result.success();
    }

    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody Account account) {
        if("ADMIN".equals(account.getRole())){
            adminService.updatePassword(account);
        }else if ("USER".equals(account.getRole())){
            userService.updatePassword(account);
        }
        return Result.success();
    }

}

